const app = new Vue({
  el: "#app",
  data: {
    books: [
      {
        id: 1,
        name: "《算法》",
        data: "2006-9",
        price: 50,
        count: 1,
      },
      {
        id: 2,
        name: "《编程之美》",
        data: "2008-9",
        price: 68,
        count: 1,
      },
      {
        id: 3,
        name: "《大话数据结构》",
        data: "2003-9",
        price: 56,
        count: 1,
      },
      {
        id: 4,
        name: "《算法竞赛》",
        data: "2006-9",
        price: 38,
        count: 1,
      },
    ],
  },
  methods: {
    getFinalPrice(price) {
      return "￥" + price.toFixed(2);
    },
    dec(index) {
      this.books[index].count--;
    },
    add(index) {
      this.books[index].count++;
    },
    removeClick(index) {
      this.books.splice(index, 1);
    },
  },
  computed: {
    totalPrice() {
      let totalPrice = 0;
      //1.
      // for (let i = 0; i < this.books.length; i++) {
      //   totalPrice += this.books[i].price * this.books[i].count;
      // }
      // return totalPrice;

      //2.for(let i in this.books)
      // for (let i in this.books) {
      //   const book = this.books[i];
      //   totalPrice += book.price * book.count;
      // }
      // return totalPrice;

      //3.for(let i of this.book)
      // for (let item of this.books) {
      //   totalPrice += item.price * item.count;
      // }
      // return totalPrice;

      //4.reduce
      return this.books.reduce(function (preValue, book) {
        return preValue + book.price * book.count;
      }, 0);
    },
  },
  //过滤器
  filters: {
    showPrice(price) {
      return "￥" + price.toFixed(2);
    },
  },
});
